const fetch = require('node-fetch');
const config = require('config')
const logger = require('../utils').getLogger(__filename);
const { key: customerKey, secret: customerSecret, url } = config.get('agora')

// 拼接客户 ID 和客户密钥
const plainCredential = customerKey + ":" + customerSecret;
// 使用 base64 进行编码
encodedCredential = Buffer.from(plainCredential).toString('base64');
authorizationField = "Basic " + encodedCredential;

module.exports = class AgoraAPIRequest {
	constructor({ options }) {
		this.logger = logger;
		this.baseUrl = url;
		this.options = Object.assign({
			method: 'POST',
			headers: {
				'Authorization': authorizationField,
				'Content-Type': 'application/json;charset=utf-8'
			}
		}, options);
	}


	post(path = '/dev/v1/projects', options) {
		let opts = Object.assign({}, this.options, options);
		let url = `${this.baseUrl}${path}`;
		this.logger.debug(`request post url:${url}`);
		this.logger.debug(`request body:${JSON.stringify(opts.body)}`);
		return fetch(url, opts);
	}

	get(path, options) {
		let opts = Object.assign({}, this.options, options, { method: 'GET' });
		let url = `${this.baseUrl}${path}`;
		this.logger.debug(`request get url:${url}`);
		this.logger.debug(`request options:${JSON.stringify(opts)}`);
		return fetch(url, opts);
	}

};
